package org.platform.processor.task.job;

import lombok.extern.slf4j.Slf4j;
import org.platform.mo.bussmo.task.TaskReport;
import org.platform.processor.diagnose.DiagnoseRecordProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zeromq.ZMQ;

import javax.annotation.PostConstruct;
import java.util.Arrays;

/**
 * 对应<远程监控接口>文档中 3.4.3 任务上报接口 部分
 * 用于接收上报的任务信息
 *
 * @author FengJie
 * @date 2018/7/11
 */
@Component
@Slf4j
public class ReceiveTaskReportJob {
    private static final String TOPIC = "RcvTaskQueue";
    private static final String ADDR = "tcp://127.0.0.1:28881";
    private static final int HEAD = 22;
    private static final int TAIL = 4;

    @Autowired
    private DiagnoseRecordProcessor processor;


    //TODO 1.当前使用的主题 端口 最终需要和廖必金确认,最终以 [配置文件]的方式使用  2.统一使用线程池的方式管理线程

    @PostConstruct
    public void init() {
        ZMQ.Context context = ZMQ.context(1);
        ZMQ.Socket socket = context.socket(ZMQ.SUB);
        socket.connect(ADDR);
        socket.subscribe(TOPIC);
        new ReceiveThread(socket).start();
    }

    /**
     * 初始化zeroMQ,用于接收数据
     */
    private class ReceiveThread extends Thread {
        private ZMQ.Socket socket;

        ReceiveThread(ZMQ.Socket socket) {
            this.socket = socket;
        }

        @Override
        @SuppressWarnings("InfiniteLoopStatement")
        public void run() {
            while (true) {
                try {
                    //第一次接收到的是主题  第二次接收到的是内容
                    String topic = socket.recvStr(0);
                    if (TOPIC.equals(topic)) {
                        byte[] recv = socket.recv();
                        //截取固定位数据
                        byte[] device = Arrays.copyOfRange(recv, HEAD, recv.length - TAIL);
                        TaskReport.TaskList taskList = TaskReport.TaskList.parseFrom(device);
                        TaskReport.WorkSchInfo schInfo = taskList.getSchInfo();
                        processor.saveWorkSchInfo(schInfo);
                    }
                } catch (Exception e) {
                    log.error("解析【任务上报】参数异常:", e);
                }
            }
        }
    }
}
